﻿using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EventsTest.Models;

namespace EventsTest.Controllers
{
    public class AjaxLongPollingController : Controller
    {
        //
        // GET: /AjaxLongPolling/
		static object lockObj = new object();
		static List<ChatMessage> LatestChatmessages = new List<ChatMessage>();

        public ActionResult Index()
        {
            return View();
        }

		public void SendMessage(ChatMessage chat)
		{
			lock (lockObj)
			{
				LatestChatmessages.Add(chat);
			}
		}

		public JsonResult Connect()
		{
			return Json(new { count = LatestChatmessages.Count });
		}

		public JsonResult GetLatestMessages(int lastCount)
		{
			int i = 0;
			while (i < 30 && lastCount == LatestChatmessages.Count)
			{
				System.Threading.Thread.Sleep(1000);
			}
			if (lastCount < LatestChatmessages.Count)
			{
				object value = new {
					count = LatestChatmessages.Count,
					messages = LatestChatmessages.GetRange(lastCount, LatestChatmessages.Count - lastCount)
				};
				return Json(value);
			}
			return null;
		}
    }
}
